<template>
	
  <view class="contain" @touchmove.stop.prevent>
		<view class="form pos">
			<view><image src="https://guangxins.oss-cn-shenzhen.aliyuncs.com/images/bg/title.png" mode="widthFix"></image></view>
			<view class="switchmode" @click="changLoginMode">
				<text>{{switchmode}}</text>
			</view>
			<view class="inputform" v-if="switchmode==='验证码登录'">
				<view class="uinput">
					<u-input :placeholder="telplaceholder"
					 type="number"
					:customStyle="{'width':'550rpx'}" 
					:placeholderStyle="{'color':'#FFF'}" border="bottom" v-model="userCount" fontSize="22" color="#FFF" @focus="foucs('tel')" @blur="blur('tel')" @change="phonechange" maxlength="11"></u-input>
				</view>
				<view class="uinput">
					<u-input :placeholder="msgplaceholder" 
					type="number"
					:customStyle="{'width':'550rpx'}" 
					:placeholderStyle="{'color':'#FFF'}" border="bottom" v-model="pwdVal" fontSize="22" color="#FFF" @focus="foucs('msg')" @blur="blur('msg')" @change="codechange" maxlength="4"></u-input>
				</view> 
				
			</view> <!-- inputform End -->
			<view class="inputform" v-if="switchmode==='身份证登录'">
				<view class="uinput">
					<u-input :placeholder="userIdCardplaceholder"
					 type="number"
					:customStyle="{'width':'550rpx'}" 
					:placeholderStyle="{'color':'#FFF'}" border="bottom" v-model="userIdCard" fontSize="22" color="#FFF" @focus="idcardfoucs('idcard')" @blur="idcardblur('idcard')" @change="idcardchange"></u-input>
				</view>
				<view class="uinput">
					<u-input :placeholder="userLoginPwdplaceholder" 
					type="password"
					:customStyle="{'width':'550rpx'}" 
					:placeholderStyle="{'color':'#FFF'}" border="bottom" v-model="userLoginPwd" fontSize="22" color="#FFF" @focus="idcardfoucs('loginpwd')" @blur="idcardblur('loginpwd')" @change="loginpwdchange"></u-input>
				</view> 
				
			</view> <!-- inputform End -->			
			
			
			<view class="readxieyi">
				<view class="ra">
					 <u-checkbox shape="circle" :checked="checked" iconSize="18" size="25" @change="checkselected"></u-checkbox>
				</view>
				<view class="rb" @click="goxieyi">我已阅读并同意《服务协议》及《隐私政策》</view>
			</view>
			<view class="codebtn" v-if="switchmode==='验证码登录'">
				<u-button :type="btnType" shape="circle" 
				:customStyle="btncustomStyle" @click="getCode"
				:disabled="isSend">{{codeTips}}</u-button>
			</view>
			<view class="submitbtn">
				<u-button :type="btnType" :customStyle="loginStyle" shape="circle" text="登录" @click="startLogin"></u-button>
				<u-button type="primary" :customStyle="{'background':'#000;','border':'0px','opacity':'0.4'}" shape="circle" text="暂不登录" @click="skip"></u-button>
			</view>
			
			
			<!-- 刷新 -->
			<view class="reload" @click="reloadPage">刷新</view>
			
		</view>
  </view>

</template>

<script setup lang="ts">
import { ref,reactive } from 'vue'
import { GoUrl } from '@/utils/utils'	
import {  onLoad,onShow,onShareAppMessage,onShareTimeline } from '@dcloudio/uni-app'
import { userStore } from '@/stores/userStore'
import { getSchool } from '@/common/common.js'



// import { bus } from '@/utils/bus'
let { hasLogin,userData } = userStore();
const store = userStore()


let defaultLogo="https://guangxins.oss-cn-shenzhen.aliyuncs.com/images/bg/loginbg.jpg";
let avatar=ref(defaultLogo);
const BASE_URL=import.meta.env.VITE_API_URL; 



// let winWidth=ref(uni.$tools.GetScreenWidth());
// let winHeight=ref(uni.$tools.GetScreenHeigth());

let switchmode=ref('验证码登录');

let keyid=ref(''); //用于识别第三方id
let userIdCard=ref('');
let userLoginPwd=ref('');

let timestart=ref(false);
let btnType=ref("primary");
let uCode=ref(); //申请对象
let codeTips=ref("获取验证码");
let codeValue=ref("");
let timeCount=ref(59);
let timer=null;
let checked=ref(false);

let isSend=ref(false);

let userCount=ref("");
let pwdVal=ref("");
let loginCode=ref("");
let isGetLoginCode=ref(false);

let telplaceholder=ref("请输入手机号(新号自动注册)");
let msgplaceholder=ref("请输入验证码");

let userIdCardplaceholder=ref("请输入您的身份证号码");
let userLoginPwdplaceholder=ref("请输入登录密码");

let schoolname=ref('');
let schoolnick=ref('');


const reloadPage=()=>{
	uni.$tools.GoUrl("/pages/login/login",1);
}

const skip=()=>{
	uni.$tools.GoUrl("/pages/index/index",2);
}


const goxieyi=()=>{
	store.backRouter=store.xieyiLink;
	uni.$tools.GoUrl("/pages/webview/webview");
}


const foucs=(focusstr:string)=>{
	if(focusstr==='tel'){
		telplaceholder.value="";
	}
	if(focusstr==='msg'){
		msgplaceholder.value="";
	}
}

const blur=(blurstr:string)=>{
	if(blurstr==='tel'){
		if(userCount.value===""){
			telplaceholder.value="请输入手机号(新号自动注册)";
		}else{
			telplaceholder.value="";
			uni.setStorageSync("TempSavePhoneNumber",userCount.value);
		}
	}
	if(blurstr==='msg'){
		if(pwdVal.value===""){
			msgplaceholder.value="请输入验证码";
		}else{
			msgplaceholder.value="";
		}
	}	
}


const idcardfoucs=(focusstr:string)=>{
	if(focusstr==='idcard'){
		userIdCardplaceholder.value="";
	}
	if(focusstr==='loginpwd'){
		userLoginPwdplaceholder.value="";
	}
}

const idcardblur=(blurstr:string)=>{
	if(blurstr==='idcard'){
		if(userIdCard.value===""){
			userIdCardplaceholder.value="请输入您的身份证号码";
		}else{
			userIdCardplaceholder.value="";
		}
	}
	if(blurstr==='loginpwd'){
		if(userLoginPwd.value===""){
			userLoginPwdplaceholder.value="请输入登录密码";
		}else{
			userLoginPwdplaceholder.value="";
		}
	}	
	
} //idcardblur End



let shareObj=reactive({
	title: '广心智康', //分享的名称
	summary:'广心智康',
	mpId: 'wx4527d18e23ee784a', //此处配置微信小程序的AppId
});


const updateLoginTime=()=>{
	let paraData={
		id:userData.userinfo.id
	}
	console.log("更新时间参数:",paraData);
	uni.$tools.Reqeust('/api/updateLoginTime',paraData,'POST').then((res:any)=>{
		console.log(res);
	});	
}

const changLoginMode=()=>{
	if(switchmode.value==='身份证登录'){
		switchmode.value="验证码登录";
	}else{
		switchmode.value="身份证登录";
	}
}


const checkselected=()=>{
	checked.value=!checked.value;
	console.log("checked.value",checked.value);
}


let btncustomStyle=reactive({
		"border":"0px",
		"height":"28px",
		"background":"#ccc !important",
		"color":"#FFF"	
});
let loginStyle=reactive({
	"border":"0px",
	"background":"#ccc !important",
	"color":"#FFF",
	"opacity":"1"
});


//手机号输入事件
const phonechange=(e:string)=>{
	//console.log("手机号输入事件:",e);
	if(e.length===11){
		btncustomStyle=reactive({
				"border":"0px",
				"height":"28px",
				"background":"#2979FF !important",
				"color":"#FFF"	
		});
		if(pwdVal.value.length===4){
			loginStyle=reactive({
				"border":"0px",
				"background":"#2979FF !important",
				"color":"#FFF",
				"opacity":"1"
			});			
		}
	}else{
		btncustomStyle=reactive({
				"border":"0px",
				"height":"28px",
				"background":"#ccc !important",
				"color":"#FFF"	
		});		
	}
}


//身份证输入事件
const idcardchange=(e:string)=>{
	console.log("身份证事件:",e);
	userData.binduseridcard=e;
	if(e==='') userIdCard.value='';
	 if(e.length>0 && userLoginPwd.value!=''){
		loginStyle=reactive({
			"border":"0px",
			"background":"#2979FF !important",
			"color":"#FFF",
			"opacity":"1"
		});
	 }else{
		loginStyle=reactive({
			"border":"0px",
			"background":"#ccc !important",
			"color":"#FFF",
			"opacity":"1"
		});	 
	 }
}


const loginpwdchange=(e:string)=>{
	 console.log("登录密码事件:",e);
	 console.log("登录值",userLoginPwd.value);
	 if(e==='') userLoginPwd.value='';
	 if(userIdCard.value!='' && e.length>0){
		loginStyle=reactive({
			"border":"0px",
			"background":"#2979FF !important",
			"color":"#FFF",
			"opacity":"1"
		});
	 }else{
		loginStyle=reactive({
			"border":"0px",
			"background":"#ccc !important",
			"color":"#FFF",
			"opacity":"1"
		});	 
	 }
}

//验证码输入事件
const codechange=(e:string)=>{
	console.log("验证码输入事件:",e);
	if(e.length===4){
		if(checkPhone()===false) return;
		loginStyle=reactive({
			"border":"0px",
			"background":"#2979FF !important",
			"color":"#FFF",
			"opacity":"1"
		});
	}else{
		loginStyle=reactive({
			"border":"0px",
			"background":"#ccc !important",
			"color":"#FFF",
			"opacity":"1"
		});		
	}
}





onShareAppMessage(()=>{
       return {
		   title: '广心智康', //分享的名称
		   path: '/pages/index/index',//分享详情页面时，需要把所需参数代入
		   mpId: 'wx4527d18e23ee784a', //此处配置微信小程序的AppId
	   };
});

onShareTimeline(()=>{
       return {
		   title: '广心智康', //分享的名称
		   type:0,
		   summary:'广心智康',
	   };
})


//参数说明
//keyid=fuyuan
//nick=gangcheng 或者 nick=ershiyi
const saveData=(evt:any)=>{
	
	if(evt!=null && evt.q!=null){ //这里要从二维码扫入场景进来才会有q
		console.log("evt",decodeURIComponent(evt.q)); 
		let tempkeyid=decodeURIComponent(evt.q).split('?')[1].replace("id=",""); //附属id
		console.log("保存keyid",tempkeyid)
		if(tempkeyid.indexOf('&')!=-1){  //fuyuan&nick=ershiyi
		
			schoolnick.value=tempkeyid.split('&')[1].replace("nick=",""); //nick=ershiyi
			schoolname.value=getSchool(schoolnick.value);
			uni.setStorageSync("school",schoolname.value);
			
			keyid.value=tempkeyid.split('&')[0];
			uni.setStorageSync("keyid",keyid.value);
			uni.setStorageSync("schoolnick",schoolnick.value);
			
			console.log("扫码-keyid:",keyid.value);
			console.log("扫码-学校编码:",schoolnick.value);
			console.log("扫码-当前学校:",schoolname.value);
			
		}else{
			keyid.value=tempkeyid;
			uni.setStorageSync("keyid",tempkeyid);			
		}
	}
	
	
	if(evt!=null && evt.keyid!=null){ //学校别名
		uni.setStorageSync("keyid",evt.keyid);
		console.log("当前evt.keyid:",evt.keyid);
	}
	if(evt!=null && evt.nick!=null){ //学校别名x
		schoolname.value=getSchool(evt.nick);
		uni.setStorageSync("school",schoolname.value);
		console.log("当前学校:",schoolname.value);
	}
}

const getLoginCode=()=>{
	if(isGetLoginCode.value===false){
		uni.login({
			  provider: 'weixin',
			  onlyAuthorize:true,
			  success:e=> {
				//登录。注册会员信息
				if(e.errMsg==='login:ok' && e.code!=null){
					loginCode.value=e.code;
					isGetLoginCode.value=true;
					console.log("微信 login code:",loginCode.value);							
				}
			  }
		});	
	}
}

onLoad(async (evt)=>{
	
	let savePhoneNumber=uni.getStorageSync("TempSavePhoneNumber") || null;
	if(savePhoneNumber!=null){
		userCount.value=savePhoneNumber;
		btncustomStyle=reactive({
				"border":"0px",
				"height":"28px",
				"background":"#2979FF !important",
				"color":"#FFF"	
		});
	}
	
	console.log("onLoad evt",evt);
	saveData(evt); //保存识别用户数据
	getLoginCode();
});


onShow(()=>{
	//console.log("888");
	if(uni.getStorageSync("token")!=null && uni.getStorageSync("token")!=''){
		userData.binduseridcard="";
		updateLoginTime();
		uni.$tools.GoUrl("/pages/mine/mine",2);
	}
	if(userData.binduseridcard!=''){
		userIdCard.value=userData.binduseridcard;
	}
})




//获取验证码
const getCode=()=>{
	
	getLoginCode();
	
	isSend.value=true;
	
	// console.log("请输入手机号")
	// uni.$tools.Toast("请输入手机号");
	pwdVal.value="";
	loginStyle=reactive({
		"border":"0px",
		"background":"#ccc !important",
		"color":"#FFF",
		"opacity":"1"
	});	
	
	// //保存用户信息，后续使用
	store.$state.phone=userCount.value;
	
	// //保存用户账号
	if(checked.value){
		console.log("记住账号...");
		uni.setStorageSync("userCount",userCount.value);
	}else{
		uni.removeStorageSync("userCount");
	}
	
	
	if(checkPhone()===false) return;
	
	
	 timestart.value=true;
	 
	 console.log("timestart.value",timestart.value);
	 
	btnType.value="info";
	if(timer!=null) clearInterval(timer);
	timer=setInterval(()=>{
		if(timeCount.value<=0){
			if(timer!=null) clearInterval(timer);
			timer=null;
			btnType.value="primary";
			isSend.value=false;
			timeCount.value=59;
			codeTips.value="获取验证码";
			timestart.value=false;
			return;
		}
		codeTips.value=timeCount.value+"秒后获取";
		timeCount.value--;
	},1000);
	
	
	
	/*
	if(timestart.value){
		console.log("isSend.value",isSend.value);
		uni.$tools.Toast("验证码已发送！网络可能存在延迟 请注意查收");
		//return;
	}
	//*/
	

	// setTimeout(()=>{
	// 	uni.$tools.Toast("验证码已发送 请注意查收！网络可能存在延迟 请耐心等待");
	// },1000);
	
	
	let paraData={
		phoneNumber:userCount.value,
		sessionId:(uni.getStorageSync("sid")===null || uni.getStorageSync("sid")==="")?null:uni.getStorageSync("sid")
	}
	console.log("电话参数:",paraData);
	uni.$tools.Reqeust('/api/sendMessage',paraData,'POST').then((res:any)=>{
			console.log('发送验证码结果:',res);
			if (res.data.code == 200) {
				//这里保存sessionid
				uni.setStorageSync("sid",res.data.sid);
				timestart.value=true;
				btnType.value="info";
				if(timer!=null) clearInterval(timer);
				timer=setInterval(()=>{
					if(timeCount.value<=0){
						if(timer!=null) clearInterval(timer);
						timer=null;
						btnType.value="primary";
						isSend.value=false;
						timeCount.value=59;
						codeTips.value="获取验证码";
						timestart.value=false;
						return;
					}
					codeTips.value=timeCount.value+"秒后获取";
					timeCount.value--;
				},1000);
				setTimeout(()=>{
					uni.$tools.Toast("验证码已发送！网络可能存在延迟 请注意查收");
				},1000);
			}else{
				uni.$tools.Toast(res.data.msg);
				isSend.value=false;
			}
	})
}


const checkPhone=()=>{
	if (!/\S/.test(userCount.value)) {
		uni.$tools.Toast("请输入手机号");
		isSend.value=false;
		return false;
	}
	const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
	if (!regMobile.test(userCount.value)) {
		uni.$tools.Toast("手机号码有误");
		isSend.value=false;
		return false;
	}
	return true;
}


//身份证登录
const idcardLogin=()=>{
	if(!/\S/.test(userIdCard.value)){
		uni.$tools.Toast("请输入身份证号码");
		return;
	}	
	if(!/\S/.test(userLoginPwd.value)){
		uni.$tools.Toast("请输入登录密码");
		return;
	}	
	
	// console.log(checked.value);
	if(checked.value===false){
		uni.$tools.Toast("请勾选并同意服务协议");
		return;	
	}
	
	let paraData={
		idcard:userIdCard.value,
		loginpwd: userLoginPwd.value,
		logincode:loginCode.value
	}
	console.log("登录参数:",paraData);
	uni.$tools.Reqeust('/api/idcardlogin',paraData,'POST').then((res:any)=>{
			console.log('登录结果:',res);
			if (res.data.code == 200) {
				
				store.$state.hasLogin=true;
				uni.setStorageSync("token",res.data.data.token); //用于接口 Authorization验证
				store.$state.token=res.data.data.token;
				store.$state.userData.userinfo=res.data.data;
				uni.$tools.Toast("登录成功");
			
				uni.setStorageSync("hasLogin",true);
				
				
				let jurl="/pages/index/index";
				
				//优先跳转到第三方
				if((keyid.value!='' && keyid.value==='fuyuan') || (uni.getStorageSync("keyid")!='' && uni.getStorageSync("keyid")==='fuyuan')){
					jurl="/pages/fushubindcheck/fushubindcheck";
					uni.$tools.GoUrl("/pages/jumpurl/jumpurl?url="+jurl); //跳转到绑定身份证
					return;
				}
				jurl="/pages/index/index";
				uni.$tools.GoUrl("/pages/jumpurl/jumpurl?url="+jurl); 
				//uni.$tools.GoUrl("/pages/index/index",2);

			}else{
				uni.$tools.Toast(res.data.msg);
			}
	})	
}







//手机验证码登录
const phoneLogin=()=>{

	//console.log("isSend",isSend.value);
	
	if(checkPhone()===false) return;
	
	if(isSend.value===false){
		uni.$tools.Toast("请获取短信验证码");
		return;
	}

	if(!/\S/.test(pwdVal.value)){
		uni.$tools.Toast("请输入短信验证码");
		return;
	}
	
	// console.log(checked.value);
	if(checked.value===false){
		uni.$tools.Toast("请勾选并同意服务协议");
		return;	
	}
	
	
	//uni.$tools.Toast("登录成功");
	let paraData={
		phoneNumber:userCount.value,
		code: pwdVal.value,
		logincode:loginCode.value,
		sessionId:(uni.getStorageSync("sid")===null || uni.getStorageSync("sid")==="")?null:uni.getStorageSync("sid")
	}
	console.log("phone登录参数:",paraData);
	uni.$tools.Reqeust('/api/login',paraData,'POST').then((res:any)=>{
			console.log('登录结果:',res);
			if (res.data.code == 200) {
				
				//移除
				uni.removeStorageSync("TempSavePhoneNumber");
				
				store.$state.hasLogin=true;
				uni.setStorageSync("token",res.data.data.token); //用于接口 Authorization验证
				store.$state.token=res.data.data.token;
				store.$state.userData.userinfo=res.data.data;
				uni.$tools.Toast("登录成功");
			
				uni.setStorageSync("hasLogin",true);
				
				let jurl="/pages/index/index";
				
				//优先跳转到第三方 -- 心理疏导
				if((keyid.value!='' && keyid.value==='fuyuan') || (uni.getStorageSync("keyid")!='' && uni.getStorageSync("keyid")==='fuyuan')){
					jurl="/pages/fushubindcheck/fushubindcheck";
					uni.$tools.GoUrl("/pages/jumpurl/jumpurl?url="+jurl,1); //跳转到绑定身份证
					return;
				}
				
				
				//优先跳转到第三方 -- 量表测评
				if((keyid.value!='' && keyid.value==='ceping') || (uni.getStorageSync("keyid")!='' && uni.getStorageSync("keyid")==='ceping')){
					jurl="/pages/ceping/ceping";
					uni.$tools.GoUrl("/pages/jumpurl/jumpurl?url="+jurl,1); //跳转到绑定身份证
					return;
				}
				
				
				//优先跳转到第三方 -- 获取量表测评结果
				if((keyid.value!='' && keyid.value==='lbreport') || (uni.getStorageSync("keyid")!='' && uni.getStorageSync("keyid")==='lbreport')){
					jurl="/pages/getcepingresullt/getcepingresullt";
					uni.$tools.GoUrl("/pages/jumpurl/jumpurl?url="+jurl,1); //跳转到绑定身份证
					return;
				}
				
				if(res.data.data.utype==='商家'){
					jurl="/pages/buy/buy";
					uni.$tools.GoUrl("/pages/jumpurl/jumpurl?url="+jurl); 
				}else{
					jurl="/pages/index/index";
					uni.$tools.GoUrl("/pages/jumpurl/jumpurl?url="+jurl); 
					//检查用户是否已绑定
					// if(res.data.data!=null){
					// 	let h5link=res.data.data.h5link;
					// 	let bindcode=res.data.data.bindcode;
					// 	//let accessUrl="/pages/webview/webview?link=123456";
					// 	let accessUrl="/pages/webview/webview";
					// 	store.backRouter=h5link;
					// 	//console.log("accessUrl==>",accessUrl);
					// 	if(bindcode!=null && bindcode!=''){
					// 		//用户已绑定，直接跳查询
					// 		uni.$tools.GoUrl(accessUrl);
					// 	}else{
					// 		//用户还未绑定
					// 		uni.$tools.GoUrl("/pages/binduser/binduser",1);
					// 	}
					// }
				}
			}else{
				uni.$tools.Toast(res.data.msg);
			}
	})
}





//身份证登录
//验证码登录
const startLogin=()=>{
	console.log(switchmode.value);
	if(switchmode.value==='身份证登录'){
		idcardLogin();
	}else{
		phoneLogin();
	}	
}

</script>
<style>
	page{
		
	}
	/deep/.input-placeholder{
		color:#FFF !important;
		font-size:36rpx !important;
	}
	/deep/.u-button{
		height:28px;
		padding:0px 10px !important;
	}
</style>
<style lang="scss" scoped>
	@import "login.scss";
</style>
